package com.zhongshengnetwork.rightbe.common;

import android.app.Activity;
//import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.dbmodel.LogindbModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CopyModel;
import com.zhongshengnetwork.rightbe.gsonmodel.DateModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangInfoModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.LangPublishActivity;
import com.zhongshengnetwork.rightbe.login.BDThirdActivity;
import com.zhongshengnetwork.rightbe.login.LoginActivity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import static android.content.Context.CLIPBOARD_SERVICE;

public class CommonUtils {

	// 可以用异常来做校验
	/**
	 * 判断字符串是否是整数
	 */
	public static boolean isInteger(String value) {
		try {
			// Integer.parseInt(value);
			Long.parseLong(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	/**
	 * 判断字符串是否是浮点数
	 */
	public static boolean isDouble(String value) {
		try {
			Double.parseDouble(value);
			if (value.contains("."))
				return true;
			return false;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	/**
	 * 判断字符串是否是数字
	 */
	public static boolean isNumber(String value) {
		return isInteger(value) || isDouble(value);
	}

	//jsonstring转json
	public static JSONObject stringToJson(String jsonString){
		try {
			JSONObject a = new JSONObject(jsonString);
			return a;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//操作异常
			return null;
		}
	}

	//jsonstring转jsonarray
	public static JSONArray stringToJsonArray(String jsonString){
		try {
			JSONArray a = new JSONArray(jsonString);
			return a;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//操作异常
			return null;
		}
	}

	//string(逗号分隔)转array
	public static List<String> stringToArrayList(String string){
		string.replaceAll(" ","");
		List l = new ArrayList();
		l = Arrays.asList(string.split(","));
		return l;
	}

	//string(逗号分隔)转array
	public static List<String> stringToArrayListByMaoHao(String string){
		string.replaceAll(" ","");
		List l = new ArrayList();
		l = Arrays.asList(string.split(":"));
		return l;
	}

	public static String listToString(List<String> stringList){
		if (stringList==null) {
			return null;
		}
		StringBuilder result=new StringBuilder();
		boolean flag=false;
		for (String string : stringList) {
			if (flag) {
				result.append(",");
			}else {
				flag=true;
			}
			result.append(string);
		}
		return result.toString();
	}
	
	//从缓存获取用户id
    public static String getUserIdFromRedis(String jsonString){
    	try {
			JSONObject a = new JSONObject(jsonString);
			return a.getString("userid");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//操作异常
			return "";
		}
    }
    
  //从缓存获取用户头像
    public static String getUserHeaderFromRedis(String jsonString){
    	try {
			JSONObject a = new JSONObject(jsonString);
			return a.getString("header");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//操作异常
			return "";
		}
    }
    
  //从缓存获取用户昵称
    public static String getUserNickNameFromRedis(String jsonString){
    	try {
			JSONObject a = new JSONObject(jsonString);
			return a.getString("nickname");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//操作异常
			return "";
		}
    }
    
    //获取消息唯一id
    public static String getMessageUid(){
    	return UUID.randomUUID().toString().toUpperCase();
    }
    
    //判断字符串是否为空
    public static boolean isEmpty(String string){
    	if(string == null){
    		return true;
    	}
    	return string.trim().isEmpty();
    }
    
    //生成群id
    public static String getGroupId(){
    	String groupid = "";
    	for(int i = 0; i < 11; i++){
    		int x=(int)(Math.random()*10);
    		groupid += x;
    	}
    	return groupid;
    }
    
    //生成用户id
    public static String getUserId(){
    	String userid = "";
    	for(int i = 0; i < 10; i++){
    		int x=(int)(Math.random()*10);
    		userid += x;
    	}
    	return userid;
    }
    
    //整理字符串
    public static String formatString(String string){
    	if(string == null){
    		return "";
    	}
    	return string;
    }

	// 四舍五入，保留number类型数值的decimalDigit位小数位数
	// 传入double类型的数值和想要保留的小数位数
	public static double numberFormat(double number, int decimalDigit){
		NumberFormat numberFormat = NumberFormat.getNumberInstance();
		numberFormat.setMaximumFractionDigits(decimalDigit);
		double result = Double.parseDouble(numberFormat.format(number));
		return result;
	}
    
    //生成唯一uuid
    public static String getUUID(){
    	String uuid = UUID.randomUUID().toString();
    	return uuid.replace("-", "").toUpperCase();
    }
    
    //判断手机号是否合法
    public static boolean isMobileNO(String mobiles){    
    	Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");     	  
    	Matcher m = p.matcher(mobiles);  
    	return m.matches();   
    }  
    
  //生成6位随机码
    public static String getCode(){
    	String code = "";
    	for(int i = 0; i < 6; i++){
    		int x=(int)(Math.random()*10);
    		code += x;
    	}
    	return code;
    }
    
    //生成唯一订单号
    public static String getOrderIdByUUID(){
		int machineId = 1;
		int hashCodeV = UUID.randomUUID().toString().hashCode();
		if(hashCodeV < 0){
			hashCodeV = - hashCodeV;
		}
		return machineId+String.format("%015d", hashCodeV);
	}
    
    //日期转时间戳
    public static long dateToTime(String dateString, String format){
    	SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date;
		try {
			date = sdf.parse(dateString);
			return date.getTime();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return System.currentTimeMillis();
		} 
    }
    
    //时间戳转日期
    public static String timeToDate(long time){
		//long time=1277106667;
		Date date=new Date(time);
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String str=format.format(date);
		//System.out.println(str);
        return str;
    }

	//时间转简单日期
	public static String timeToSimpleDate(long time){
		//long time=1277106667;
		Date date=new Date(time);
		SimpleDateFormat format=new SimpleDateFormat("yyyy.MM.dd");
		String str=format.format(date);
		//System.out.println(str);
		return str;
	}
    
    //时间转时间id
    public static String timeToTimeid(long time){
		Date date=new Date(time);
		SimpleDateFormat format=new SimpleDateFormat("yyyyMMdd");
		String str=format.format(date);
		str += "000000";
        return str;
    }
    
    //取时间时分秒毫秒数
    public static long timeToNumber(long time){
    	long haomiao = time%1000;
    	time = time/1000;
		Date date=new Date(time);
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String str=format.format(date);
		str = str.substring(11, 19);
		str = str.replace(":", "");
		String hmStr= "";
		if(haomiao < 10){
			hmStr = "00"+haomiao;
		}else if(haomiao < 100){
			hmStr = "0"+haomiao;
		}else{
			hmStr = ""+haomiao;
		}
		str+=hmStr;
		System.out.print("str="+str+"\r\n");
        return Long.valueOf(str);
    }
    
  //生成6位幸运号码
    public static String getLuckyNumber(){
    	String code = "";
    	for(int i = 0; i < 6; i++){
    		int x=(int)(Math.random()*10);
    		if(i == 0 && x == 0){
    			x = 1;
    		}
    		code += x;
    	}
    	return code;
    }
    
    //生成AES密匙
    public static String getAESKey(String userid){
    	String skey = MD5.GetMD5Code(userid);
		skey = skey.substring(0, 16);
		return skey;
    }
    
    //获取在某范围内的随机幸运号码
    public static int[] GetRandomSequence(int total)
    {
        int[] sequence = new int[total];
        int[] output = new int[total];

        for (int i = 0; i < total; i++)
        {
            sequence[i] = i;
        }

        Random random = new Random();

        int end = total - 1;

        for (int i = 0; i < total; i++)
        {
            //int num = random.Next(0, end + 1);
        	int num = random.nextInt(end+1);
            output[i] = sequence[num]+10000001;
            sequence[num] = sequence[end];
            end--;
        }

        return output;
    }
    
  //获取在某范围内的随机幸运号码
    public static String GetRandomSeq(int total)
    {
        int[] sequence = new int[total];
        String seq = "";

        for (int i = 0; i < total; i++)
        {
            sequence[i] = i;
        }

        Random random = new Random();

        int end = total - 1;

        for (int i = 0; i < total; i++)
        {
            //int num = random.Next(0, end + 1);
        	int num = random.nextInt(end+1);
            seq += (sequence[num]+10000001);
            if(i==total-1){
            	
            }else{
            	seq += ",";
            }
            sequence[num] = sequence[end];
            end--;
        }

        return seq;
    }
    
    //获取抽奖整数
    public static int getRedPrizeNumber(int range){
    	int x=1+(int)(Math.random()*range);
    	return x;
    }

	//上传字节文件到七牛云
	public static void uploadBytesToQiniu(String token, final String baseUrl, final String name, byte[] data, final QiniuCallBack qiniuCallBack){
		try {
			if (CommonUtils.isEmpty(token) || CommonUtils.isEmpty(baseUrl) || CommonUtils.isEmpty(name) || data == null || data.length == 0){
				LangPublishActivity.uploadError("七牛云sdk上传图片参数缺少");
				if (qiniuCallBack != null){
					qiniuCallBack.onError(null);
				}
				return;
			}
			if (CustomApplication.uploadManager == null){
				LangPublishActivity.uploadError("七牛云上传对象为空");
				CustomApplication.customApplication.initQiniu();
			}

			CustomApplication.uploadManager.put(data, name, token, new UpCompletionHandler() {
				@Override
				public void complete(String key, ResponseInfo info, JSONObject response) {
					if (info.isOK() == true){//上传成功
						if (qiniuCallBack != null){
							String url = baseUrl+name;
							qiniuCallBack.onSuccess(url);
						}
					}else {//上传失败
						LangPublishActivity.uploadError("七牛云sdk上传图片错误信息："+CommonUtils.formatString(info.error));
						if (qiniuCallBack != null){
							qiniuCallBack.onError(null);
						}
					}
				}
			},null);
		}catch (Exception e){
			LangPublishActivity.uploadError("七牛云sdk上传图片异常信息："+CommonUtils.formatString(e.getMessage()));
			if (qiniuCallBack != null){
				qiniuCallBack.onError(null);
			}
		}
	}

	//上传单个文件到七牛云
    public static void uploadFileToQiniu(String token, final String baseUrl, final String name, String filePath, final QiniuCallBack qiniuCallBack){
		CustomApplication.uploadManager.put(filePath, name, token, new UpCompletionHandler() {
			@Override
			public void complete(String key, ResponseInfo info, JSONObject response) {
				if (info.isOK() == true){//上传成功
					if (qiniuCallBack != null){
						String url = baseUrl+name;
						qiniuCallBack.onSuccess(url);
					}
				}else {//上传失败
					if (qiniuCallBack != null){
						qiniuCallBack.onError(null);
					}
				}
			}
		},null);
	}

	//上传多个文件到七牛云
	public static void uploadFilesToQiniu(final String token, final String baseUrl, String filesPath, final QiniuCallBack qiniuCallBack){
	   final List<String> fileList = CommonUtils.stringToArrayList(filesPath);
		if (fileList == null || fileList.size() == 0){
			if (qiniuCallBack != null){
				qiniuCallBack.onError(null);
				return;
			}
		}
		final QiniuUploadModel model = new QiniuUploadModel();
		final long time = System.currentTimeMillis();
		final String name = time+"1"+".jpg";
		CustomApplication.uploadManager.put(fileList.get(0), name, token, new UpCompletionHandler() {
			@Override
			public void complete(String key, ResponseInfo info, JSONObject response) {
				if (info.isOK() == true){//上传第一张大图成功
					String url = baseUrl+name;
					//将保存在本地的图片取出并缩小后显示在界面上
					Bitmap bitmap = BitmapFactory.decodeFile(fileList.get(0));
					model.setUrl(url);
					model.setH(bitmap.getHeight()+"");
					model.setW(bitmap.getWidth()+"");
					Bitmap newBitmap = getZoomImage(bitmap,120,120);//zoomBitmap(bitmap, 100, 100);
					//由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
					bitmap.recycle();
					final String name = time+"1s"+".jpg";
					CustomApplication.uploadManager.put(CommonUtils.bitmapToBytes(newBitmap), name, token, new UpCompletionHandler() {
						@Override
						public void complete(String key, ResponseInfo info, JSONObject response) {
							if (info.isOK() == true){//上传第一张小图成功
                                model.setSurl(baseUrl+name);
								if (fileList.size() > 1){
									final String name2 = time+"2"+".jpg";
									CustomApplication.uploadManager.put(fileList.get(1), name2, token, new UpCompletionHandler() {
										@Override
										public void complete(String key, ResponseInfo info, JSONObject response) {
											if (info.isOK() == true){//上传第二张大图成功
												//将保存在本地的图片取出并缩小后显示在界面上
												Bitmap bitmap = BitmapFactory.decodeFile(fileList.get(1));
												model.setUrl(model.getUrl()+","+baseUrl+name2);
												model.setW(model.getW()+","+bitmap.getWidth());
												model.setH(model.getH()+","+bitmap.getHeight());
												Bitmap newBitmap = getZoomImage(bitmap,120,120);//zoomBitmap(bitmap, 100, 100);
												//由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
												bitmap.recycle();
												final String name2 = time+"2s"+".jpg";
												CustomApplication.uploadManager.put(CommonUtils.bitmapToBytes(newBitmap), name2, token, new UpCompletionHandler() {
													@Override
													public void complete(String key, ResponseInfo info, JSONObject response) {
														if (info.isOK() == true){//上传第二张小图成功
															model.setSurl(model.getSurl()+","+baseUrl+name2);
															if (fileList.size() > 2){
																final String name3 = time + "3" + ".jpg";
																CustomApplication.uploadManager.put(fileList.get(2), name3, token, new UpCompletionHandler() {
																	@Override
																	public void complete(String key, ResponseInfo info, JSONObject response) {
																		if (info.isOK() == true){//上传第三张大图成功
																			//将保存在本地的图片取出并缩小后显示在界面上
																			Bitmap bitmap = BitmapFactory.decodeFile(fileList.get(2));
																			model.setUrl(model.getUrl()+","+baseUrl+name3);
																			model.setW(model.getW()+","+bitmap.getWidth());
																			model.setH(model.getH()+","+bitmap.getHeight());
																			Bitmap newBitmap = getZoomImage(bitmap,120,120);//zoomBitmap(bitmap, 100, 100);
																			//由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
																			bitmap.recycle();
																			final String name3 = time+"3s"+".jpg";
																			CustomApplication.uploadManager.put(CommonUtils.bitmapToBytes(newBitmap), name3, token, new UpCompletionHandler() {
																				@Override
																				public void complete(String key, ResponseInfo info, JSONObject response) {
																					if (info.isOK() == true){//上传第三张小图成功
																						model.setSurl(model.getSurl()+","+baseUrl+name3);
																						if (qiniuCallBack != null){
																							qiniuCallBack.onModelSuccess(model);
																						}
																					}else {//上传第三张小图失败
																						if (qiniuCallBack != null){
																							qiniuCallBack.onError(null);
																							return;
																						}
																					}
																				}
																			},null);
																		}else {//上传第三张大图失败
																			if (qiniuCallBack != null){
																				qiniuCallBack.onError(null);
																				return;
																			}
																		}
																	}
																},null);
															}else {//仅上传两张
																if (qiniuCallBack != null){
																	qiniuCallBack.onModelSuccess(model);
																}
															}
														}else {//上传第二张小图失败
															if (qiniuCallBack != null){
																qiniuCallBack.onError(null);
																return;
															}
														}
													}
												},null);

											}else {//上传第二张大图失败
												if (qiniuCallBack != null){
													qiniuCallBack.onError(null);
													return;
												}
											}
										}
									},null);
								}else {//仅上传一张
									if (qiniuCallBack != null){
										qiniuCallBack.onModelSuccess(model);
									}
								}

							}else {//上传第一张小图失败
								if (qiniuCallBack != null){
									qiniuCallBack.onError(null);
									return;
								}
							}
						}
					},null);
				}else {//上传第一张大图失败
					if (qiniuCallBack != null){
						qiniuCallBack.onError(null);
						return;
					}
				}
			}
		},null);

	}

	/** 缩放Bitmap图片 **/
	public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
		int w = bitmap.getWidth();
		int h = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidth = ((float) width / w);
		float scaleHeight = ((float) height / h);
		matrix.postScale(scaleWidth, scaleHeight);// 利用矩阵进行缩放不会造成内存溢出
		Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
		return newbmp;
	}

	//Bitmap转byte
	public static byte[] bitmapToBytes(Bitmap bmp){
		if (bmp == null){
			System.out.print("图片是空的\n");
		}
		ByteArrayOutputStream output = new ByteArrayOutputStream();//初始化一个流对象
		bmp.compress(Bitmap.CompressFormat.JPEG, 100, output);//把bitmap100%高质量压缩 到 output对象里
		//bmp.recycle();//自由选择是否进行回收
		if (bmp != null && !bmp.isRecycled()){
			bmp.recycle();
			bmp = null;
			System.gc();  //提醒系统及时回收
		}
		byte[] result = output.toByteArray();//转换成功了
		try {
			output.close();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	//字符串转换成金额
	public static String textToMoney(String text){
		if (text == null || text.length() == 0){
			return "0.00";
		}else {
			DecimalFormat df = new DecimalFormat("0.00");
			return String.valueOf(df.format(Double.valueOf(text)));
		}
	}

	/**
	 * 图片的缩放方法
	 *
	 * @param bitmap  ：源图片资源
	 * @param maxSize ：图片允许最大空间  单位:KB
	 * @return
	 */
	public static Bitmap getZoomImage(Bitmap bitmap, double maxSize) {
		if (null == bitmap) {
			return null;
		}
		if (bitmap.isRecycled()) {
			return null;
		}

		// 单位：从 Byte 换算成 KB
		double currentSize = bitmapToByteArray(bitmap, false).length / 1024;
		// 判断bitmap占用空间是否大于允许最大空间,如果大于则压缩,小于则不压缩
		while (currentSize > maxSize) {
			// 计算bitmap的大小是maxSize的多少倍
			double multiple = currentSize / maxSize;
			// 开始压缩：将宽带和高度压缩掉对应的平方根倍
			// 1.保持新的宽度和高度，与bitmap原来的宽高比率一致
			// 2.压缩后达到了最大大小对应的新bitmap，显示效果最好
			bitmap = getZoomImage(bitmap, bitmap.getWidth() / Math.sqrt(multiple), bitmap.getHeight() / Math.sqrt(multiple));
			currentSize = bitmapToByteArray(bitmap, false).length / 1024;
		}
		return bitmap;
	}

	/**
	 * 图片的缩放方法
	 *
	 * @param orgBitmap ：源图片资源
	 * @param newWidth  ：缩放后宽度
	 * @param newHeight ：缩放后高度
	 * @return
	 */
	public static Bitmap getZoomImage(Bitmap orgBitmap, double newWidth, double newHeight) {
		if (null == orgBitmap) {
			return null;
		}
		if (orgBitmap.isRecycled()) {
			return null;
		}
		if (newWidth <= 0 || newHeight <= 0) {
			return null;
		}

		// 获取图片的宽和高
		float width = orgBitmap.getWidth();
		float height = orgBitmap.getHeight();
		// 创建操作图片的matrix对象
		Matrix matrix = new Matrix();
		// 计算宽高缩放率
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(orgBitmap, 0, 0, (int) width, (int) height, matrix, true);
		return bitmap;
	}

	/**
	 * bitmap转换成byte数组
	 *
	 * @param bitmap
	 * @param needRecycle
	 * @return
	 */
	public static byte[] bitmapToByteArray(Bitmap bitmap, boolean needRecycle) {
		if (null == bitmap) {
			return null;
		}
		if (bitmap.isRecycled()) {
			return null;
		}

		ByteArrayOutputStream output = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
		if (needRecycle) {
			bitmap.recycle();
		}

		byte[] result = output.toByteArray();
		try {
			output.close();
		} catch (Exception e) {
			//Log.e(TAG, e.toString());
		}
		return result;
	}

	/**
	 * 获取缩略图
	 * @param imagePath:文件路径
	 * @param width:缩略图宽度
	 * @param height:缩略图高度
	 * @return
	 */
	public static Bitmap getImageThumbnail(String imagePath, int width, int height) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true; //关于inJustDecodeBounds的作用将在下文叙述
		Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
		int h = options.outHeight;//获取图片高度
		int w = options.outWidth;//获取图片宽度
		int scaleWidth = w / width; //计算宽度缩放比
		int scaleHeight = h / height; //计算高度缩放比
		int scale = 1;//初始缩放比
		if (scaleWidth < scaleHeight) {//选择合适的缩放比
			scale = scaleWidth;
		} else {
			scale = scaleHeight;
		}
		if (scale <= 0) {//判断缩放比是否符合条件
			scale = 1;
		}
		options.inSampleSize = scale;
		// 重新读入图片，读取缩放后的bitmap，注意这次要把inJustDecodeBounds 设为 false
		options.inJustDecodeBounds = false;
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		// 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
		bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		return bitmap;
	}

	public static Bitmap getImageThumbnail(Bitmap bitmap, int width, int height) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true; //关于inJustDecodeBounds的作用将在下文叙述
		int h = options.outHeight;//获取图片高度
		int w = options.outWidth;//获取图片宽度
		int scaleWidth = w / width; //计算宽度缩放比
		int scaleHeight = h / height; //计算高度缩放比
		int scale = 1;//初始缩放比
		if (scaleWidth < scaleHeight) {//选择合适的缩放比
			scale = scaleWidth;
		} else {
			scale = scaleHeight;
		}
		if (scale <= 0) {//判断缩放比是否符合条件
			scale = 1;
		}
		options.inSampleSize = scale;
		// 重新读入图片，读取缩放后的bitmap，注意这次要把inJustDecodeBounds 设为 false
		options.inJustDecodeBounds = false;
		// 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
		bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		return bitmap;
	}

	/**
	 * 判断应用是否已经启动
	 * @param context 一个context
	 * @param packageName 要判断应用的包名
	 * @return boolean
	 */
	public static boolean isAppAlive(Context context, String packageName){
		/*
		ActivityManager activityManager =
				(ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningAppProcessInfo> processInfos
				= activityManager.getRunningAppProcesses();
		for(int i = 0; i < processInfos.size(); i++){
			if(processInfos.get(i).processName.equals(packageName)){
				//Log.i("NotificationLaunch",
						//String.format("the %s is running, isAppAlive return true", packageName));
				return true;
			}
		}
		*/
		//Log.i("NotificationLaunch",
				//String.format("the %s is not running, isAppAlive return false", packageName));
		return false;
	}

	//获取当前时间的小时
	public static int getHourOfDay(){
		Calendar c = Calendar.getInstance();
		return c.get(Calendar.HOUR_OF_DAY);
	}

	//获取当前时间的星期几
	public static int getDayOfWeek(){
		Calendar c = Calendar.getInstance();
		return c.get(Calendar.DAY_OF_WEEK);
	}

	//获取类型
	public static String getLifeTypeName(int type){
		String str = "";
		if(type == -1){
			str = "广告";
		}else if(type == 1){
			str = "视频";
		}else if(type == 2){
			str = "直播";
		}else if(type == 3){
			str = "美图";
		}else if(type == 4){
			str = "美文";
		}else if(type == 5){
			str = "成语";
		}else if(type == 6){
			str = "悬疑";
		}else if(type == 7){
			str = "故事";
		}else if(type == 8){
			str = "搞笑";
		}else if(type == 9){
			str = "常识";
		}else if(type == 101){
			str = "段子";
		}
		return str;
	}

	public static int getLifeTypeByName(String str){
		int type = 0;
		if(str.equals("广告")){
			type = -1;
		}else if(str.equals("视频")){
			type = 1;
		}else if(str.equals("直播")){
			type = 2;
		}else if(str.equals("美图")){
			type = 3;
		}else if(str.equals("美文")){
			type = 4;
		}else if(str.equals("成语")){
			type = 5;
		}else if(str.equals("悬疑")){
			type = 6;
		}else if(str.equals("故事")){
			type = 7;
		}else if(str.equals("搞笑")){
			type = 8;
		}else if(str.equals("常识")){
			type = 9;
		}else if(str.equals("段子")){
			type = 101;
		}
		return type;
	}

	/**
	 * 给定一个长字符串内容，返回一个数组
	 *
	 * @param content
	 *            所有的内容
	 * @param count
	 *            需要每段截取的长度
	 * @return 所有分段的数组list
	 */
	public static List<String> getListFromContent(String content, int count) {
		List<String> list = new ArrayList<String>();
		// 获取String的总长度
		int contentLength = content.length();

		if (contentLength < count) {
			list.add(content);
		} else {

			int begin = 0;
			// 获取需要切割多少段
			int cutCount = contentLength / count;

			int cutCounts = contentLength % count;

			// 获取切割段的长度
			if (cutCounts != 0) {
				cutCount++;
			}

			for (int i = 1; i <= cutCount; i++) {
				String temp;
				// 不是最后一段
				if (i != cutCount) {

					temp = content.substring(begin, count * i);

				} else {
					temp = content.substring(begin, contentLength);
				}

				begin = count * i;
				list.add(temp);
			}

		}

		return list;
	}

	public static DateModel getDateModel(long timesamp){
		Calendar calendar = Calendar.getInstance();

		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int date = calendar.get(Calendar.DATE);


		calendar.setTime(new Date(timesamp*1000));

		DateModel dateModel = new DateModel();
		dateModel.setYear(calendar.get(Calendar.YEAR)+"");
        dateModel.setMonth((calendar.get(Calendar.MONTH)+1)+"");
        if (year == calendar.get(Calendar.YEAR) && month == calendar.get(Calendar.MONTH) && date == calendar.get(Calendar.DATE)){
        	dateModel.setDay("今日");
		}else {
			dateModel.setDay(
					calendar.get(Calendar.DATE)+"");
		}
        dateModel.setHour(calendar.get(Calendar.HOUR_OF_DAY)+"");
        dateModel.setMinute(
				calendar.get(Calendar.MINUTE)+"");
        dateModel.setSecond(calendar.get(Calendar.SECOND)+"");
        dateModel.setWeek(calendar.get(Calendar.DAY_OF_WEEK)+"");
		return dateModel;
	}

	public static DateModel getDateModelForNumber(long timesamp){
		Calendar calendar = Calendar.getInstance();

		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int date = calendar.get(Calendar.DATE);


		calendar.setTime(new Date(timesamp*1000));

		DateModel dateModel = new DateModel();
		dateModel.setYear(calendar.get(Calendar.YEAR)+"");
		dateModel.setMonth((calendar.get(Calendar.MONTH))+"");
		dateModel.setDay(
				calendar.get(Calendar.DATE)+"");
		dateModel.setHour(calendar.get(Calendar.HOUR_OF_DAY)+"");
		dateModel.setMinute(
				calendar.get(Calendar.MINUTE)+"");
		dateModel.setSecond(calendar.get(Calendar.SECOND)+"");
		dateModel.setWeek(calendar.get(Calendar.DAY_OF_WEEK)+"");
		return dateModel;
	}

	public static String getNewDateTime(long timesamp){
		boolean isDay = false;
		StringBuffer sb = new StringBuffer();
		long t = timesamp;
		long time = System.currentTimeMillis() - t;
		long mill = (long) Math.ceil(time /1000);//秒前
		long minute = (long) Math.ceil(time/60/1000.0f);// 分钟前
		long hour = (long) Math.ceil(time/60/60/1000.0f);// 小时
		long day = (long) Math.ceil(time/24/60/60/1000.0f);// 天前
		if (day - 1 > 0) {
			sb.append(day + "天");
			isDay = true;
		} else if (hour - 1 > 0) {
			if (hour >= 24) {
				sb.append("1天");
				isDay = true;
			} else {
				sb.append(hour + "小时");
			}
		} else if (minute - 1 > 0) {
			if (minute == 60) {
				sb.append("1小时");
			} else {
				sb.append(minute + "分钟");
			}
		} else if (mill - 1 > 0) {
			if (mill == 60) {
				sb.append("1分钟");
			} else {
				sb.append(mill + "秒");
			}
		} else {
			sb.append("刚刚");
		}
		if (!sb.toString().equals("刚刚")) {
			sb.append("前");
		}
		if (isDay == true){
			return TimeUtils.timeStamp2Date(timesamp);
		}
		return sb.toString();
	}

	/**
	 *  时间戳格式转换
	 */
	static String dayNames[] = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
	public static String getNewChatTime(long timesamp) {
        boolean isDay = false;
		StringBuffer sb = new StringBuffer();
		long t = timesamp;
		long time = System.currentTimeMillis() - t;
		long mill = (long) Math.ceil(time /1000);//秒前
		long minute = (long) Math.ceil(time/60/1000.0f);// 分钟前
		long hour = (long) Math.ceil(time/60/60/1000.0f);// 小时
		long day = (long) Math.ceil(time/24/60/60/1000.0f);// 天前
		if (day - 1 > 0) {
			sb.append(day + "天");
			isDay = true;
		} else if (hour - 1 > 0) {
			if (hour >= 24) {
				sb.append("1天");
				isDay = true;
			} else {
				sb.append(hour + "小时");
			}
		} else if (minute - 1 > 0) {
			if (minute == 60) {
				sb.append("1小时");
			} else {
				sb.append(minute + "分钟");
			}
		} else if (mill - 1 > 0) {
			if (mill == 60) {
				sb.append("1分钟");
			} else {
				sb.append(mill + "秒");
			}
		} else {
			sb.append("刚刚");
		}
		if (!sb.toString().equals("刚刚")) {
			sb.append("前");
		}
        if (isDay == true){
			return TimeUtils.getNewChatTime(timesamp);
		}
		return sb.toString();

		/*
		String result = "";
		Calendar todayCalendar = Calendar.getInstance();
		Calendar otherCalendar = Calendar.getInstance();
		otherCalendar.setTimeInMillis(timesamp);

		String timeFormat="M月d日 HH:mm";
		String yearTimeFormat="yyyy年M月d日 HH:mm";
		String am_pm="";
		int hour=otherCalendar.get(Calendar.HOUR_OF_DAY);
		if(hour>=0&&hour<6){
			am_pm="凌晨";
		}else if(hour>=6&&hour<12){
			am_pm="早上";
		}else if(hour==12){
			am_pm="中午";
		}else if(hour>12&&hour<18){
			am_pm="下午";
		}else if(hour>=18){
			am_pm="晚上";
		}
		timeFormat="M月d日 "+ am_pm +"HH:mm";
		yearTimeFormat="yyyy年M月d日 "+ am_pm +"HH:mm";

		boolean yearTemp = todayCalendar.get(Calendar.YEAR)==otherCalendar.get(Calendar.YEAR);
		if(yearTemp){
			int todayMonth=todayCalendar.get(Calendar.MONTH);
			int otherMonth=otherCalendar.get(Calendar.MONTH);
			if(todayMonth==otherMonth){//表示是同一个月
				int temp=todayCalendar.get(Calendar.DATE)-otherCalendar.get(Calendar.DATE);
				switch (temp) {
					case 0:
						result = getHourAndMin(timesamp);
						break;
					case 1:
						result = "昨天 " + getHourAndMin(timesamp);
						break;
					case 2:
					case 3:
					case 4:
					case 5:
					case 6:
						int dayOfMonth = otherCalendar.get(Calendar.WEEK_OF_MONTH);
						int todayOfMonth=todayCalendar.get(Calendar.WEEK_OF_MONTH);
						if(dayOfMonth==todayOfMonth){//表示是同一周
							int dayOfWeek=otherCalendar.get(Calendar.DAY_OF_WEEK);
							if(dayOfWeek!=1){//判断当前是不是星期日     如想显示为：周日 12:09 可去掉此判断
								result = dayNames[otherCalendar.get(Calendar.DAY_OF_WEEK)-1] + getHourAndMin(timesamp);
							}else{
								result = getTime(timesamp,timeFormat);
							}
						}else{
							result = getTime(timesamp,timeFormat);
						}
						break;
					default:
						result = getTime(timesamp,timeFormat);
						break;
				}
			}else{
				result = getTime(timesamp,timeFormat);
			}
		}else{
			result=getYearTime(timesamp,yearTimeFormat);
		}
		return result;
		*/
	}

	/**
	 * 当天的显示时间格式
	 * @param time
	 * @return
	 */
	public static String getHourAndMin(long time) {
		SimpleDateFormat format = new SimpleDateFormat("HH:mm");
		return format.format(new Date(time));
	}

	/**
	 * 不同一周的显示时间格式
	 * @param time
	 * @param timeFormat
	 * @return
	 */
	public static String getTime(long time,String timeFormat) {
		SimpleDateFormat format = new SimpleDateFormat(timeFormat);
		return format.format(new Date(time));
	}

	/**
	 *
	 * @param time  1541569323155
	 * @param pattern yyyy-MM-dd HH:mm:ss
	 * @return 2018-11-07 13:42:03
	 */
	public static String getDate2String(long time, String pattern) {
		Date date = new Date(time);
		SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.getDefault());
		return format.format(date);
	}

	/**
	 * 不同年的显示时间格式
	 * @param time
	 * @param yearTimeFormat
	 * @return
	 */
	public static String getYearTime(long time,String yearTimeFormat) {
		SimpleDateFormat format = new SimpleDateFormat(yearTimeFormat);
		return format.format(new Date(time));
	}

	//获取登录状态
	public static boolean isLogin(){
		if (CustomApplication.loginModel == null){
			CustomApplication.loginModel = new LogindbModel();
			CustomApplication.loginModel.setUid("1");//默认用户id
			CustomApplication.loginModel.setToken("");
		}
		if (CommonUtils.isEmpty(CustomApplication.loginModel.getToken())){
			return false;
		}
		if (CustomApplication.isAutoLogin == true){
			return false;
		}
		return true;
	}

	public static boolean deleteFileByPath(String filePath){
		File file = new File(filePath);
		if(file.exists()){
			return file.delete();
		}else {
			return false;
		}
	}

	/**
	 * @param bmp 获取的bitmap数据
	 * @param picName 自定义的图片名
	 */
	public static void saveBmp2GalleryForShare(Bitmap bmp, String picName) {

		String fileName = null;

		//系统相册目录
		String galleryPath= CommonUtils.getFile(Environment.DIRECTORY_PICTURES)
				+ File.separator + Environment.DIRECTORY_DCIM
				+File.separator+"Camera"+File.separator;

		// 声明文件对象
		File file = null;
		// 声明输出流
		FileOutputStream outStream = null;

		try {
			// 如果有目标文件，直接获得文件对象，否则创建一个以filename为名称的文件
			file = new File(galleryPath, picName+ ".jpg");
			// 获得文件相对路径
			fileName = file.toString();
			// 获得输出流，如果文件中有内容，追加内容
			outStream = new FileOutputStream(fileName);
			if (null != outStream) {
				bmp.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
			}

		} catch (Exception e) {
			e.getStackTrace();
		}finally {
			try {
				if (outStream != null) {
					outStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		//通知相册更新
		MediaStore.Images.Media.insertImage(CustomApplication.mContext.getContentResolver(),
				bmp, fileName, null);
		Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		Uri uri = Uri.fromFile(file);
		intent.setData(uri);
		CustomApplication.mContext.sendBroadcast(intent);

		ToastUtil.show(CustomApplication.mContext,"图片保存成功");

	}

	/**
	 * @param bmp 获取的bitmap数据
	 * @param picName 自定义的图片名
	 */
	public static void saveBmp2Gallery(Bitmap bmp, String picName) {

		String fileName = null;
		//系统相册目录
//		String galleryPath= CommonUtils.getFile(Environment.DIRECTORY_PICTURES)
//				+ File.separator + Environment.DIRECTORY_PICTURES
//				+File.separator+"WeiJu"+File.separator;

		String galleryPath = "";
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){//适配android 11及以上
			galleryPath = CustomApplication.mContext.getExternalFilesDir(null)+File.separator+"Pictures"+File.separator;//qq分享必须要这个路径;
		}else {
			galleryPath= Environment.getExternalStorageDirectory()
					+ File.separator + Environment.DIRECTORY_DCIM
					+File.separator+"WeiJu"+File.separator;
		}

		// 声明文件对象
		File file = null;
		// 声明输出流
		FileOutputStream outStream = null;

		try {
			// 如果有目标文件，直接获得文件对象，否则创建一个以filename为名称的文件
			file = new File(galleryPath, picName+ ".jpg");
			// 获得文件相对路径
			fileName = file.toString();
			// 获得输出流，如果文件中有内容，追加内容
			outStream = new FileOutputStream(fileName);
			if (null != outStream) {
				bmp.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
			}

		} catch (Exception e) {
			e.getStackTrace();
		}finally {
			try {
				if (outStream != null) {
					outStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
          }
        //通知相册更新
        MediaStore.Images.Media.insertImage(CustomApplication.mContext.getContentResolver(),
				bmp, fileName, null);
		Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		Uri uri = Uri.fromFile(file);
		intent.setData(uri);
		CustomApplication.mContext.sendBroadcast(intent);

		ToastUtil.show(CustomApplication.mContext,"图片保存成功");

	}


	/**
	 * @param bmp 获取的bitmap数据
	 * @param picName 自定义的图片名
	 */
	public static String getSaveBmp2Gallery(Bitmap bmp, String picName) {

		String fileName = null;
		//系统相册目录
//		String galleryPath= Environment.getExternalStorageDirectory()
//				+ File.separator + Environment.DIRECTORY_DCIM
//				+File.separator+"WeiJu"+File.separator;

//		String galleryPath= CommonUtils.getFile(Environment.DIRECTORY_PICTURES)
//				+ File.separator + Environment.DIRECTORY_DCIM
//				+File.separator+"Camera"+File.separator;//qq分享必须要这个路径
		String galleryPath = "";
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){//适配android 11及以上
			galleryPath = CustomApplication.mContext.getExternalFilesDir(null)+File.separator+"Pictures"+File.separator;//qq分享必须要这个路径;
		}else {
//			galleryPath= Environment.getExternalStorageDirectory()
//				+ File.separator + Environment.DIRECTORY_DCIM
//				+File.separator+"WeiJu"+File.separator;
			galleryPath= CommonUtils.getFile(Environment.DIRECTORY_PICTURES)
				+ File.separator + Environment.DIRECTORY_DCIM
				+File.separator+"Camera"+File.separator;//qq分享必须要这个路径
		}


		// 声明文件对象
		File file = null;
		// 声明输出流
		FileOutputStream outStream = null;

		try {
			// 如果有目标文件，直接获得文件对象，否则创建一个以filename为名称的文件
			file = new File(galleryPath, picName+ ".jpg");
			// 获得文件相对路径
			fileName = file.toString();
			// 获得输出流，如果文件中有内容，追加内容
			outStream = new FileOutputStream(fileName);
			if (null != outStream) {
				bmp.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
			}

		} catch (Exception e) {
			e.getStackTrace();
			return null;
		}finally {
			try {
				if (outStream != null) {
					outStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
		}
		//通知相册更新
		MediaStore.Images.Media.insertImage(CustomApplication.mContext.getContentResolver(),
				bmp, fileName, null);
		Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		Uri uri = Uri.fromFile(file);
		intent.setData(uri);
		CustomApplication.mContext.sendBroadcast(intent);
		return uri.getEncodedPath();//qq分享必须要这个路径
		//return fileName;

	}

	//保存文件到指定路径
	public static boolean saveImageToGallery(Context context, Bitmap bmp) {
		// 首先保存图片  dearxy是可以改的
		String storePath = CommonUtils.getFile(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + "Camera";
		File appDir = new File(storePath);
		if (!appDir.exists()) {
			appDir.mkdir();
		}
		String fileName = System.currentTimeMillis() + ".jpg";
		File file = new File(appDir, fileName);
		try {
			FileOutputStream fos = new FileOutputStream(file);
			//通过io流的方式来压缩保存图片
			boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 90, fos);
			fos.flush();
			fos.close();

			//把文件插入到系统图库
			//MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);

			//保存图片后发送广播通知更新数据库
			Uri uri = Uri.fromFile(file);
			context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
			if (isSuccess) {
				return true;
			} else {
				return false;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	public static String getDisplayCount(long count){
		if (count < 1000){
			return ""+count;
		}
		if(count < 10000){
			DecimalFormat df = new DecimalFormat("#.0");
			double f = count*0.001;
			return df.format(f)+"k";
		}
		DecimalFormat df = new DecimalFormat("#.0");
		double f = count*0.0001;
		return df.format(f)+"w";
	}

	/**
	 * @Description 是否为当天24h内
	 * @author
	 * @return
	 * boolean
	 */
	public static boolean isToday(long inputtime) {
		boolean flag = false;
		Date inputJudgeDate = new Date(inputtime*1000);
		//获取当前系统时间
		long longDate = System.currentTimeMillis();
		Date nowDate = new Date(longDate);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String format = dateFormat.format(nowDate);
		String subDate = format.substring(0, 10);
		//定义每天的24h时间范围
		String beginTime = subDate + " 00:00:00";
		String endTime = subDate + " 23:59:59";
		Date paseBeginTime = null;
		Date paseEndTime = null;
		try {
			paseBeginTime = dateFormat.parse(beginTime);
			paseEndTime = dateFormat.parse(endTime);

		} catch (ParseException e) {
			return false;
		}
		if(inputJudgeDate.after(paseBeginTime) && inputJudgeDate.before(paseEndTime)) {
			flag = true;
		}
		return flag;
	}

	public static Map<String, String> json2map(String str_json) {
		Map<String, String> res = null;
		try {
			Gson gson = new Gson();
			res = gson.fromJson(str_json, new TypeToken<Map<String, String>>() {
			}.getType());
		} catch (JsonSyntaxException e) {
		}
		return res;
	}

	//参数类型是Map<String,String> 因为支付只能用string的参数。如果诸君还需要修改的话，那也可以适当的做调整
	/**
	 *
	 * map转str
	 * @param map
	 * @return
	 */
	public static String getMapToString(Map<String,String> map){
		Set<String> keySet = map.keySet();
		//将set集合转换为数组
		String[] keyArray = keySet.toArray(new String[keySet.size()]);
		//给数组排序(升序)
		Arrays.sort(keyArray);
		//因为String拼接效率会很低的，所以转用StringBuilder。博主会在这篇博文发后不久，会更新一篇String与StringBuilder开发时的抉择的博文。
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < keyArray.length; i++) {
			// 参数值为空，则不参与签名 这个方法trim()是去空格
			if (map.get(keyArray[i]).trim().length() > 0) {
				sb.append(keyArray[i]).append("=").append(map.get(keyArray[i]).trim());
			}
			if(i != keyArray.length-1){
				sb.append("&");
			}
		}
		return sb.toString();
	}

	//判断图片格式
	public static Bitmap.CompressFormat getImageType(String filePath){
		if (filePath == null || filePath.length() == 0){
			return null;
		}else if (filePath.contains(".jpg") || filePath.contains(".jpeg") || filePath.contains(".JPG") || filePath.contains(".JPEG")){
			return Bitmap.CompressFormat.JPEG;
		}else if (filePath.contains(".png") || filePath.contains(".PNG")){
			return Bitmap.CompressFormat.PNG;
		}else if (filePath.contains(".WEBP") || filePath.contains(".webp")){
			return Bitmap.CompressFormat.WEBP;
		}
		return null;
	}

	//判断文件是否存在
	public static boolean fileIsExists(String strFile)
	{
		try
		{
			File f=new File(strFile);
			if(!f.exists())
			{
				return false;
			}

		}
		catch (Exception e)
		{
			return false;
		}

		return true;
	}

	public static List<LangInfoModel> formatLangInfoList(List<LangInfoModel> list){
		if (list != null && list.size() > 0){
			List<LangInfoModel> array = new ArrayList<LangInfoModel>();
			int count = 0;
			int hotcount = 0;
			String lastUserId = "";
			for(LangInfoModel m : list){
				if (lastUserId.equals(m.getUserid())){
					count++;
					if (m.ishot() == true){
						hotcount++;
					}
				}else {
					count = 0;
					hotcount = 0;
				}
				lastUserId = m.getUserid();
				if (count > 2){
					/*
					if (hotcount == count){
                        if (count > 4){
                        	continue;
						}
					}else {
						continue;
					}
					*/
					continue;
				}
				array.add(m);
			}
			return array;
		}else {
			return list;
		}
	}

	//获取UI模式
	public static int getUIMode(){
		int uimode = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.UIModeKey, AdvertUtils.UI_Simple_Mode);
		return uimode;
	}

	//获取首页最新菜单
	public static int getHomeLatestMenuMode(){
		int menumode = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.HomeLatestMenuKey, AdvertUtils.All_Content_Mode);
		return menumode;
	}

	public static DateModel getNowDateModel(){
		Calendar calendar = Calendar.getInstance();
		DateModel dateModel = new DateModel();
		dateModel.setYear(calendar.get(Calendar.YEAR)+"");
		dateModel.setMonth((calendar.get(Calendar.MONTH)+1)+"");
		dateModel.setDay(
				calendar.get(Calendar.DATE)+"");
		dateModel.setHour(calendar.get(Calendar.HOUR_OF_DAY)+"");
		dateModel.setMinute(
				calendar.get(Calendar.MINUTE)+"");
		dateModel.setSecond(calendar.get(Calendar.SECOND)+"");
		dateModel.setWeek(calendar.get(Calendar.DAY_OF_WEEK)+"");
		return dateModel;
	}

	public static String getKey(int type){
		String s = "";
		if (type == 0){//个性模式最新列表
			s = "NewLangFragment";
		}else if (type == 1){//关注页面
		    s = "CareLangFragment";
        }else if (type == 2){//微句最新列表
		    s = "LatestLangFragment";
        }else if (type == 3){//生活分享
		    s = "ShareLangFragment";
        }else if (type == 4){//心里话
            s = "ShareLangFragment";
        }else if (type == 5){//话题探索
			s = "TopicFragment";
		}else if(type >= 10000){//首页推荐
			s = "HotLangFragment";
		}else if(type >= 1000){//个性频道
			s = "ChannelFragment";
		} else if (type >= 100){//微句类型
            s = "WeijuList";
		}
		s = s +type;
		return s;
	}


	public static void copy(Activity context, String content, boolean isOriginal, String langid){

		if (context == null){
			return;
		}

		if (CommonUtils.isEmpty(content)){
			return;
		}

		if (CommonUtils.isLogin() == false){
			Intent intent = new Intent(context, LoginActivity.class);
			context.startActivity(intent);
			return;
		}

		if (isOriginal == true){
			ToastUtil.show(context, "亲，原创内容不可以复制哦~");
			return;
		}

		try{
			ClipboardManager myClipboard = (ClipboardManager)context.getSystemService(CLIPBOARD_SERVICE);
			if (myClipboard == null){
				Toast.makeText(context, "亲，暂时不支持复制哦~",
						Toast.LENGTH_SHORT).show();
				return;
			}
			ClipData myClip = ClipData.newPlainText("text", content);
			myClipboard.setPrimaryClip(myClip);

			final int copyCount = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.CopyCountKey, 1);
			if (copyCount > 0){
				Toast.makeText(context, "内容复制成功~",
						Toast.LENGTH_SHORT).show();
			}

			if (!CommonUtils.isEmpty(langid)) {
				String lastCopyId = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.LastCopyKey, "");
				if (langid.equals(lastCopyId) == true){//复制同一条内容，不需要上传服务器
					if (copyCount > 0){
						return;
					}
				}
			}
			SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.LastCopyKey, CommonUtils.formatString(langid));


			if (content.length() > 30){
				content = content.substring(0,30);
			}
			final String title = content;

			new Thread(new Runnable() {
				@Override
				public void run() {
					final HashMap<String, String> map = new HashMap<String, String>();
					map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
					map.put("title", title);
					map.put("type","100");
					map.put("id", CommonUtils.formatString(langid));
					String url = "miniapp/"+"langappid"+"/sharelanginfo.do";
					HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
						@Override
						public void onSuccess(final String data) {
							CommonModel commonModel = GsonTools.getCommonModel(data);
							if (commonModel.getFlag().equals("1")){
								context.runOnUiThread(new Runnable() {
									@Override
									public void run() {
										CopyModel copyModel = GsonTools.getCopyModel(data);
										if (copyModel != null){
											SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.CopyCountKey, copyModel.getCount());
										}
										if (copyModel != null && copyModel.getCount() < 0){
											ClipData myClip = ClipData.newPlainText("text", "");
											myClipboard.setPrimaryClip(myClip);
											Toast.makeText(context, copyModel.getTip(),
													Toast.LENGTH_SHORT).show();
										}else {
											if (copyModel != null && copyModel.getCount() >= 0 && copyCount < 1){
												Toast.makeText(context, "内容复制成功~",
														Toast.LENGTH_SHORT).show();
											}
										}
									}
								});
							}else {
								if (commonModel.getCode().equals(Constant.UserReturnCode.CODE_10011)) {//登录过期
									context.runOnUiThread(new Runnable() {
										@Override
										public void run() {
											CustomApplication.showTip(commonModel, context);
											ClipData myClip = ClipData.newPlainText("text", "");
											myClipboard.setPrimaryClip(myClip);
											Toast.makeText(context, "登录过期，请重新登录~",
													Toast.LENGTH_SHORT).show();
										}
									});
								}
							}
						}

						@Override
						public void onError(String msg) {

						}
					});
				}
			}).start();

		}catch (Exception e){
			Toast.makeText(context, "亲，暂时不支持复制哦~",
					Toast.LENGTH_SHORT).show();
		}

	}

	//获取字符串首次出现的位置
	public static int appearNumber(String srcText, String findText) {
		int count = 0;
		int index = 0;
		while ((index = srcText.indexOf(findText, index)) != -1) {
			//index = index + findText.length();
			break;
		}
		return index;
	}

	//绑定手机号
	public static boolean bindMobile(Activity activity){
		if (CommonUtils.isLogin() == true){
			if (!CommonUtils.isEmpty(CustomApplication.loginModel.getNeed()) && CustomApplication.loginModel.getNeed().equals("1")){
				if (CommonUtils.isEmpty(CustomApplication.loginModel.getMobile())){
					Intent intent = new Intent(activity, BDThirdActivity.class);
					activity.startActivity(intent);
					return true;
				}
			}
		}
		return false;
	}

	public static File getFile(String type){
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){//适配android 11及以上
			return CustomApplication.mContext.getExternalFilesDir(type);
		}else {
            return Environment.getExternalStorageDirectory();
		}
	}

}
